package org.datacoder.geocoding.jurisdiction

import org.datacoder.util.*

class CountyService {

    def jurisdictionService
    def votingDistrictService

    static transactional = true

    /* CRUD */
    public County create(County county) throws DAOException{
        save(county)
        return county
    }
    public void save(County county) throws DAOException{
        ServiceUtils.save(county)
    }
    public void save(County county, boolean flush) throws DAOException{
        ServiceUtils.save(county, flush)
    }
    public void delete(County county){
        if(county == null){
            return
        }
        Set<VotingDistrict> votingDistricts = new HashSet<VotingDistrict>(VotingDistrict.findAllByCounty(county))
        for(votingDistrict in votingDistricts){
            votingDistrictService.delete(votingDistrict)
        }
        county.delete(flush:true)
    }
    public County merge(County county){
        return county.merge()
    }
    public County get(String countyId){
        return get(Long.parseLong(countyId))
    }
    public County get(long countyId){
        return County.get(countyId)
    }
    public Set<County> getAll(){
        return County.findAll()
    }
    /* END CRUD */

    public County getByNameAndStateOrCreate(String name, State state, String longName){
        County county = getByLongNameAndState(longName, state)
        if(county == null){
            county = new County(
                name:name,
                longName:longName,
                state:state
            )
            county = create(county)
        }
        return county
    }

    public County getByLongNameAndState(String longName, State state){
        County county = County.findByLongNameAndState(longName, state)
        return county
    }

    public County getByNameAndState(String name, State state){
        County county = County.findByNameAndState(name, state)
        return county
    }

    public Set<County> findByState(State state) {
        return County.findAllByState(state)
    }
}

